package org.jeecg.config;

import org.activiti.engine.IdentityService;
import org.activiti.spring.security.IdentityServiceUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.GlobalAuthenticationConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.core.userdetails.UserDetailsService;

//@Configuration
//@AutoConfigureBefore({org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration.class})
public class SecurityAutoConfiguration {
    public SecurityAutoConfiguration() {
    }

   /* @Configuration
    @ConditionalOnClass(
            name = {"org.activiti.rest.service.api.RestUrls", "org.springframework.web.servlet.DispatcherServlet"}
    )
    @EnableWebSecurity
    public static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
        public SecurityConfiguration() {
        }

        @Bean
        public AuthenticationProvider authenticationProvider() {
            return new BasicAuthenticationProvider();
        }

        protected void configure(HttpSecurity http) throws Exception {
            ((HttpSecurity)((ExpressionUrlAuthorizationConfigurer.AuthorizedUrl)((HttpSecurity)http.authenticationProvider(this.authenticationProvider()).csrf().disable()).authorizeRequests().anyRequest()).authenticated().and()).httpBasic();
        }
    }*/

    @Configuration
    @ConditionalOnClass({UserDetailsService.class})
    public static class UserDetailsServiceConfiguration extends GlobalAuthenticationConfigurerAdapter {
        @Autowired
        private IdentityService identityService;

        public UserDetailsServiceConfiguration() {
        }

        public void init(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(this.userDetailsService());
        }

        @Bean
        public UserDetailsService userDetailsService() {
            return new IdentityServiceUserDetailsService(this.identityService);
        }
    }
}
